/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ejercicio.practica10;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 *
 * @author manolo
 */
public class ReentrantServer implements Runnable {

    private Socket socket;
    private final ReentrantLock bloqueo = new ReentrantLock();
    private static long contador= 0;

    public ReentrantServer(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            bloqueo.lock();
            contador++;
            System.out.println("Conexión nº "+ contador);
            socket.close();
        } catch (Exception e) {
            System.out.println("Error..." + e);
        } finally {
            bloqueo.unlock();
        }

    }

    public static void main(String[] args) {
        int puerto = 2001;
        ServerSocket server = null;
        ThreadPoolExecutor ept = new ThreadPoolExecutor(10, 10, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
        Socket cable = null;
        try {
            server = new ServerSocket(puerto);
            System.out.println("Esperando solicitud de conexion...");
            while (true) {
                ept.prestartAllCoreThreads();
                cable = server.accept();
                System.out.println("Recibida solicitud de conexion...");
                ept.execute(new ReentrantServer(cable));
            }
        } catch (IOException e) {
            System.out.println("Error en sockets...");
        }
    }
}
